package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.service.ISkuStockService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author LOGIN
 * @title ProductReceiver
 * @create 2025/7/31 17:26
 * @description
 */
@Slf4j
@Component
public class ProductReceiver {

    @Autowired
    private ISkuStockService skuStockService;


    /**
     * 解锁库存
     * @param orderNo 订单号
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT,type = "direct",durable = "true"),
            key = MqConst.ROUTING_UNLOCK,
            value =@Queue(value = MqConst.QUEUE_UNLOCK,durable = "true")
    ))
    public void inLock(String orderNo, Message message, Channel channel){
        long deliveryTag = message.getMessageProperties().getDeliveryTag();  //确认字符
        try {
            log.info("解锁库存。。。"+orderNo);
            skuStockService.unlock(orderNo);

            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("解锁库存失败："+ e.getMessage());
            //      用于标识需要拒绝的具体消息  只拒绝当前这一条消息  被拒绝的消息不会重新入队
            channel.basicNack(deliveryTag,false,false);
        }
    }

}
